package com.jingdianjichi.wx.controller;


import com.jingdianjichi.wx.handler.WxChatMsgFactory;
import com.jingdianjichi.wx.handler.WxChatMsgHandler;
import com.jingdianjichi.wx.utils.MessageUtil;
import com.jingdianjichi.wx.utils.SHA1;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Objects;

/**
 * @Description: 用户接收 微信公众号 的 回调
 * @return:
 * @Author:  sky
 * @date:  2024/11/11 23:36
 */
@RestController
@Slf4j
public class CallBackController {

    private static final String token = "adwidhaidwoaid";

    @Autowired
    private WxChatMsgFactory wxChatMsgFactory;

    @RequestMapping("/test")
    public String test(){
        return "hello";
    }
    
    /**
     * @Description:  回调消息 校验阶段
     * @return:
     * @Author:  sky
     * @date:  2024/11/11 23:48
     */
    @GetMapping("/callback")
    public String callback(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("echostr") String echostr) {
        log.info("get验签请求参数：signature:{}，timestamp:{}，nonce:{}，echostr:{}",
                signature, timestamp, nonce, echostr);
        String shaStr = SHA1.getSHA1(token, timestamp, nonce, "");
        // token是共享的，手动加密，与wx服务器加密进行比较
        // 相等则校验成功，否则校验失败
        if (signature.equals(shaStr)) {
            return echostr;
        }
        return "unknown";
    }

    /**
     * @Description: 回调消息 校验完成后，拿取用户信息阶段
     *                   返回信息全部封装在 消息体里面
     *                  返回信息是xml格式的，PostMapping需要额外指定xml格式
     * @return:
     * @Author:  sky
     * @date:  2024/11/11 23:49
     */
    @PostMapping(value = "/callback", produces = "application/xml;charset=UTF-8")
    public String callback(
            @RequestBody String requestBody,
            @RequestParam("signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam(value = "msg_signature", required = false) String msgSignature) {
        log.info("接收到微信消息：requestBody：{}", requestBody);
        Map<String, String> messageMap = MessageUtil.parseXml(requestBody);
        String msgType = messageMap.get("MsgType");
        String event = messageMap.get("Event") == null ? "" : messageMap.get("Event");
        log.info("msgType:{},event:{}", msgType, event);

        StringBuilder sb = new StringBuilder();
        sb.append(msgType);
        if (!StringUtils.isEmpty(event)) {
            sb.append(".");
            sb.append(event);
        }
        // 如果是event类型，还会拼接event具体类型
        // 如果是text类型，则直接得到text，去调用text的handler
        String msgTypeKey = sb.toString();
        WxChatMsgHandler wxChatMsgHandler = wxChatMsgFactory.getHandlerByMsgType(msgTypeKey);
        if (Objects.isNull(wxChatMsgHandler)) {
            return "unknown";
        }
        String replyContent = wxChatMsgHandler.dealMsg(messageMap);
        log.info("replyContent:{}", replyContent);
        return replyContent;

    }
}

//        String fromUserName = messageMap.get("FromUserName");
//        String toUserName = messageMap.get("ToUserName");
//        String content = "<xml>\n" +
//                "  <ToUserName><![CDATA["+fromUserName+"]]></ToUserName>\n" +
//                "  <FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n" +
//                "  <CreateTime>12345678</CreateTime>\n" +
//                "  <MsgType><![CDATA[text]]></MsgType>\n" +
//                "  <Content><![CDATA[张翼飞是asb]]></Content>\n" +
//                "</xml>";
//        return content;
